package com.ev.k3cloudBusiness.service.impl;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.ev.asl.config.KisApiUrlParam;
import com.ev.framework.utils.BDException;
import com.ev.framework.utils.R;
import com.ev.k3cloudBusiness.dto.ErpInOrOutStockParam;
import com.ev.k3cloudBusiness.dto.KisStockInOrOutDto;
import com.ev.k3cloudBusiness.vo.KisApiResultVOS;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service("syncPushBillAdapter")
public class SyncPushBillAdapter {

    @Autowired
    private KisApiUrlParam kisApiUrlParam;

    /**
     * 库存调拨
     *
     * @param params 库存调拨参数
     * @return {@link R}<{@link ?}>
     */
    public KisApiResultVOS inventoryTransfer(List<ErpInOrOutStockParam> params) {
        HashMap<String, Object> requestParam = getRequestParam(1, 41, params);
        log.info("MES->KIS库存调拨参数：{}", JSON.toJSONString(requestParam));
        KisApiResultVOS kisApiResultVOS = postRequest(kisApiUrlParam.getUrl_push_bill(), requestParam);
        return kisApiResultVOS;
    }

    /**
     * 封装出入库请求参数
     * @param rob
     * @param tranType
     * @param params
     * @return
     */
    public HashMap<String, Object> getRequestParam(Integer rob, Integer tranType, List<ErpInOrOutStockParam> params) {
        List<KisStockInOrOutDto> items = params.stream().map(ErpInOrOutStockParam::voToPo).collect(Collectors.toList());
        if (tranType.equals(21)) items.forEach(item -> item.setSrcTranTypeId("81"));
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("Acct", "XRTEST");
        paramMap.put("rOB", rob);
        paramMap.put("trantype", tranType);
        paramMap.put("billEntrys", items);
        return paramMap;
    }

    public KisApiResultVOS postRequest(String url, HashMap<String, Object> paramMap) {
        String result = HttpRequest.post(url)
                .header(Header.CONTENT_TYPE, "application/json; charset=utf-8")// 头信息，多个头信息多次调用此方法即可
                .header(Header.ACCEPT, "application/json")// 头信息，多个头信息多次调用此方法即可
                // .form(paramMap)//表单内容
                .body(JSON.toJSONString(paramMap))
                .timeout(20000)// 超时，毫秒
                .execute().body();
        KisApiResultVOS apiResultVOS = JSON.parseObject(JSON.parseObject(result, String.class), KisApiResultVOS.class);
        log.info("---返回数据：" + JSON.toJSONString(result));
        // 0 为正常  1 异常
        if (ObjectUtil.isEmpty(apiResultVOS.getStatus()) || !apiResultVOS.getStatus().equals(0)) {
            throw new BDException("同步失败，请联系管理员！");
        }
        return apiResultVOS;
    }

}
